<?php

class CommoditiesController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
        $pub = Pub::find(1);
        $PATH = $pub->path;
        $type = Input::get('type');
        $tab = Input::get('tab');
        if($tab){
            $tabs = array('新奇小物','奢华大礼','缤纷礼券','旅游度假','品牌','其他');
            $commoditytabs = Commoditytab::where('tab_id',$tab)->get();
            return View::make('commodities.index_two',compact('commoditytabs','PATH','customer'));
        }else{
            $customer_id = Session::get('customer_id');
            $customer = Customer::find($customer_id);
            if(!isset($type)){
                $type = 1;
            }
            if($type == 3){
                $commodities = Commodity::where('type','>=',3)->get();
            }else{
                $commodities = Commodity::where('type',$type)->get();
            }
            return View::make('commodities.index',compact('commodities','PATH','customer'));
        }
	}


    public function buy(){
        $id = Input::get('commodity_id');
        $commodity = Commodity::find($id);
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        if($commodity->member_points > $customer->all_points-$customer->use_points){
            $enable = 0;
        }else{
            $enable = 1;
        }
        return View::make('commodities.buy',compact('customer','commodity','enable'));
    }

    /**
     * 提交到支付
     * @return mixed
     */
    public function postBuy(){
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);

        $id = Input::get('commodity_id');

        $commodity = Commodity::find($id);

        $time = $this->build_order_no(); //拼接appid + 时间

        $buyrecord = New Buyrecord();
        $buyrecord->city = $customer->city;
        $buyrecord->customer_id = $customer_id;
        $buyrecord->name = Input::get('name');
        $buyrecord->mobile = Input::get('mobile');
        $buyrecord->address = Input::get('address');
        $buyrecord->commodity_id = $id;
        $buyrecord->out_trade_no = $time;
        $buyrecord->area = $customer->area;
        $buyrecord->remark = Input::get('datetime');
        $buyrecord->save();
        $type = Input::get('type');
        if($type == '积 分 兑 换'){
            return View::make('commodities.postDui',compact('commodity','buyrecord','jsApiParameters','mount','filterins','filtercos','type','filters','time'));


        }elseif($type == '微 信 支 付'){

            $pub = Pub::find(1);



            $appid = $pub->AppID;
            $appsecret = $pub->AppSecret;


        $total = $commodity->member_price*100;
//            $total = 1;
            $body = $commodity->name;

            $openid = $customer->openid;




            $xml = '<xml>
              <openid><![CDATA['.$openid.']]></openid>
              <body><![CDATA['.$body.']]></body>
              <out_trade_no><![CDATA['.$time.']]></out_trade_no>
              <total_fee>'.$total.'</total_fee>
              <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
              <trade_type><![CDATA[JSAPI]]></trade_type>
              <appid><![CDATA['.$appid.']]></appid>
              <mch_id>1226760102</mch_id>
              <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
              <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
            </xml>';
            $arr = $this->xmlToArray($xml); //转成数组
            $str = $this->formatBizQueryParaMap($arr,false); //字典序排序 1
            $stringSignTemp = $str.'&key='.$pub->apiKey;  //把key拼接上 2
            $md5 = md5($stringSignTemp); //md5 3
            $sign = strtoupper($md5); //再转大写 获取sign 4
            $x = '<xml>
              <openid><![CDATA['.$openid.']]></openid>
              <body><![CDATA['.$body.']]></body>
              <out_trade_no><![CDATA['.$time.']]></out_trade_no>
              <total_fee>'.$total.'</total_fee>
              <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
              <trade_type><![CDATA[JSAPI]]></trade_type>
              <appid><![CDATA['.$appid.']]></appid>
              <mch_id>1226760102</mch_id>
              <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
              <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
              <sign><![CDATA['.$sign.']]></sign>
            </xml>';
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';  //把xml数据提交到这个url上
            $res = $this->xmlToArray($this->postXmlCurl($x,$url));  //返回结果为xml格式 再转成数组
            $prepay_id = ($res['prepay_id']); //得到了 prepay_id

            $jsApiParameters = $this->getParameters($appid,$prepay_id,$pub->apiKey);

            return View::make('commodities.postBuy',compact('commodity','jsApiParameters','mount','filterins','filtercos','type','filters','time'));

        }
    }


    public function success(){

        $notice = '商品购买成功！稍后将有工作人员与您联系';
        return View::make('errors.success',compact('notice'));
    }
	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//

	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        $commodity = Commodity::find(Input::get('commodity_id'));
        if($commodity->member_points > $customer->all_points-$customer->use_points){
            $notice = '兑换失败，积分不够';
            return View::make('errors.error',compact('notice'));
        }else{
            $customer->use_points = $customer->use_points+$commodity->member_points;
            $customer->save();
            $buyrecord = Buyrecord::find(Input::get('buyrecord_id'));
            $buyrecord->state = 1;
            $buyrecord->save();
            $notice = '商品兑换成功！稍后将有工作人员与您联系';
            return View::make('errors.success',compact('notice'));
        }
	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
        $pub = Pub::find(1);
        $PATH = $pub->path;
        $commodity = Commodity::find($id);
        return View::make('commodities.show',compact('commodity','PATH'));
//        var_dump($rates);
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//


	}



    /**
     *  作用：产生随机字符串，不长于32位
     */
    function createNoncestr( $length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     *  作用：设置jsapi的参数
     */
    function getParameters($appid,$prepay_id,$apiKey)
    {
        $jsApiObj["appId"] = $appid;
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=$prepay_id";
        $jsApiObj["signType"] = "MD5";

        //把上面的参数字典序排序
        $one = $this->formatBizQueryParaMap($jsApiObj,false);
        $two = $one.'&key='.$apiKey;
        $three = md5($two);
        $four= strtoupper($three);

        $jsApiObj["paySign"] = $four;
        $parameters = json_encode($jsApiObj);

        return $parameters;
    }

    //http 请求
    function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     *  作用：以post方式提交xml到对应的接口url
     */
    function postXmlCurl($xml,$url,$second=30){
        //初始化curl
        $ch = curl_init();
        //设置超时
        //curl_setopt($ch, CURLOP_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        //返回结果
        if($data){
            //curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }


    /**
     *  作用：将xml转为array
     */
    function xmlToArray($xml){
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }


    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if($urlencode){
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

    /**
     *
     * uniqid - 官方是这样说的：
     * Gets a prefixed unique identifier based on the current time in microseconds.
     */
    function build_order_no()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
